package com.gitee.wsl.jvm.okhttp.intercept.updown

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException


/**
 * User: ljx
 * Date: 2022/10/18
 * Time: 21:41
 */
class RangeInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        var request: Request = chain.request()
        val osFactory: OutputStreamFactory<*>? = request.tag(OutputStreamFactory::class.java)
        var startIndex: Long = 0
        if (osFactory != null && osFactory.offsetSize().also { startIndex = it } >= 0) {
            val rangeHeader = "bytes=$startIndex-"
            request = request.newBuilder()
                .addHeader("Range", rangeHeader)
                .tag(DownloadOffSize::class.java, DownloadOffSize(startIndex))
                .build()
        }
        return chain.proceed(request)
    }
}

class DownloadOffSize(val offSize: Long)